<template>
  <md-notice-bar :closable="closable" :time="time" :icon="icon">
    <div class="wrap" ref="wrap">
      <div class="content" :class="animationClass" ref="content" :style="contentStyle">
        <slot>{{value}}</slot>
      </div>
    </div>
  </md-notice-bar>
</template>

<script>
import { NoticeBar } from 'mand-mobile';
export default {
  name: 'notice-bar',
  data() {
    return {
      wrapWidth: 0,
      firstRound: true,
      duration: 0,
      offsetWidth: 0,
      showNoticeBar: true,
      animationClass: ''
    };
  },
  components: {
    [NoticeBar.name]: NoticeBar
  },
  props: {
    closable: {
      type: Boolean,
      default: true
    },
    time: {
      type: Number,
      default: 0
    },
    icon: {
      type: String,
      default: 'circle-alert'
    },
    value: {
      type: String,
      default: ''
    },
    delay: {
      type: [String, Number],
      default: 1
    },
    scrollable: {
      type: Boolean,
      default: true
    },
    speed: {
      type: Number,
      default: 50
    }
  },
  methods: {
    $_hide(time) {
      setTimeout(() => {
        this.isShow = false;
      }, time);
    },
    $_close() {
      this.isShow = false;
    }
  },
  computed: {
    contentStyle() {
      return {
        paddingLeft: this.wrapWidth + 'px',
        animationDelay: '0s',
        animationDuration: this.duration + 's'
      };
    }
  },
  watch: {
    value: {
      handler() {
        this.$nextTick(() => {
          const { wrap, content } = this.$refs;
          if (!wrap || !content) {
            return;
          }
          const wrapWidth = wrap.getBoundingClientRect().width;
          const offsetWidth = content.getBoundingClientRect().width;
          if (this.scrollable && offsetWidth > wrapWidth) {
            this.wrapWidth = wrapWidth;
            this.offsetWidth = offsetWidth;
            this.duration = (this.offsetWidth + this.wrapWidth) / this.speed;
            this.animationClass = 'scrolling-infinite';
          }
        });
      },
      immediate: true
    }
  }
};
</script>

<style lang="stylus" scoped>
.wrap {
  margin-right: 75px;
  overflow: hidden;
  position: relative;
  height: 100%;
}

.content {
  font-size: 24px;
  position: absolute;
  white-space: nowrap;
}

.scrolling-infinite {
  animation: notice-bar-play-infinite linear infinite both;
}

@keyframes notice-bar-play-infinite {
  to {
    transform: translate3d(-100%, 0, 0);
  }
}

::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>
